import React from 'react'
import { Mentions, Tag } from 'antd';
//todo kim-stamp 防抖、消抖（debounce）与节流（throttle）
import debounce from 'lodash/debounce';
const { Option } = Mentions;

export default class AsyncMention extends React.Component {
  constructor() {
    super();
    this.loadGithubUsers = debounce(this.loadGithubUsers, 800);  //加防抖
  }

  state = {
    search: '',
    loading: false,
    users: [],
  };

  onSearch = search => {
    this.setState({ search, loading: !!search, users: [] });
    console.log('Search:', search);
    this.loadGithubUsers(search);
  };

  loadGithubUsers(key) {
    if (!key) { this.setState({ users: [] }); return }
    fetch(`https://api.github.com/search/users?q=${key}`)
      .then(res => res.json())
      .then(({ items = [], total_count }) => {
        const { search } = this.state;
        if (search !== key) return;

        this.setState({ users: items.slice(0, 100), loading: false, total_count: total_count });
      });
  }

  render() {
    const { users, loading } = this.state;

    return (
      <Mentions style={{ width: '100%' }} loading={loading} onSearch={this.onSearch}>
        {users.map(({ login, avatar_url, id: githubId }) => (
          <Option key={login} value={login} className="antd-demo-dynamic-option">
            <img src={avatar_url} alt={login} style={{ width: 30, marginRight: 10 }} />
            <Tag>{login}</Tag> <Tag>{githubId}</Tag> <Tag>总数={this.state.total_count}</Tag>
          </Option>
        ))}
      </Mentions>
    );
  }
}